package org.ehe.business.engineer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.ehe.business.engineer.domain.EngineerEntity;
import org.ehe.business.engineer.domain.bo.EngineerBO;
import org.ehe.business.engineer.domain.dto.CreateEngineerRequest;
import org.ehe.business.engineer.domain.vo.EngineerEntityVO;
import org.ehe.business.engineer.mapper.EngineerMapper;
import org.ehe.business.engineer.service.EngineerService;
import org.ehe.business.project.domain.ProjectAssignmentEntity;
import org.ehe.business.project.service.ProjectAssignmentService;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author :zhangnn
 * @className :EngineerServiceImpl
 * @description: TODO
 * @date 2025-07-16 11:04:09
 */
@Service
@RequiredArgsConstructor
public class EngineerServiceImpl extends ServiceImpl<EngineerMapper, EngineerEntity> implements EngineerService {

    private final ProjectAssignmentService projectAssignmentService;

    /**
     * 创建工程师
     */
    public int createEngineer(EngineerEntity engineer) {
        engineer.setStatus(1);
        int insert = this.baseMapper.insert(engineer);
        return insert;
    }

    /**
     * 修改信息
     * @param request
     * @return
     */
    @Override
    public int updateEngineer(EngineerEntity request) {
        int i = this.baseMapper.updateById(request);
        return i;
    }

    /**
     * 获取工程师详细信息
     */
    public EngineerEntity getEngineerDetail(Long engineerId) {
        return this.baseMapper.selectById(engineerId);
    }

    /**
     * 获取所有工程师
     */
    public TableDataInfo<EngineerEntityVO> getAllEngineers(EngineerBO engineerBO, PageQuery query) {
        List<EngineerEntityVO> vos = new ArrayList<>();
        LambdaQueryWrapper<EngineerEntity> lqw = new LambdaQueryWrapper<EngineerEntity>()
            .eq(EngineerEntity::getStatus, 1)
            .like(StringUtils.isNotBlank(engineerBO.getName()), EngineerEntity::getName, engineerBO.getName())
            .orderByDesc(EngineerEntity::getCreateTime);

        Page<EngineerEntityVO> list = this.baseMapper.selectVoPage(query.build(),lqw);
        for (EngineerEntityVO ee : list.getRecords()) {
            EngineerEntityVO vo = new EngineerEntityVO();
            //工程师ID
            Long engineerId = ee.getId();
            //获取被分配的项目总数量
            List<ProjectAssignmentEntity>  assignmentEntities =  projectAssignmentService.list(new QueryWrapper<ProjectAssignmentEntity>().lambda()
                    .eq(ProjectAssignmentEntity::getEngineerId,engineerId).eq(ProjectAssignmentEntity::getDelFlag,0));
            //项目总数
            int count = assignmentEntities.size();
            vo.setSumProject(count);
            // 使用Stream分组统计状态数量
            Map<String, Long> statusCountMap = assignmentEntities.stream()
                    // 过滤状态不为null的记录
                    .filter(entity -> entity.getStatus() != null)
                    // 按状态分组，并统计每组数量
                    .collect(Collectors.groupingBy(
                            ProjectAssignmentEntity::getStatus,
                            Collectors.counting()
                    ));

            // 进行中
            long inProgress = statusCountMap.getOrDefault(1, 0L);
            // 已完成
            long completeProject = statusCountMap.getOrDefault(2, 0L);
            // 已取消
            long cancelled = statusCountMap.getOrDefault(3, 0L);
            // 失败
            long failProject = statusCountMap.getOrDefault(4, 0L);
            //超期
            long outProject = statusCountMap.getOrDefault(5, 0L);
            vo.setInProject(inProgress);
            vo.setSuccessProject(completeProject);
            vo.setFailProject(cancelled+failProject);
            vo.setOverdueProject(outProject);
            //赋值
            vo.setId(ee.getId());
            vo.setName(ee.getName());
            vo.setHireDate(ee.getHireDate());
            vo.setCurrentLevel(ee.getCurrentLevel());
            vo.setCurrentSalary(ee.getCurrentSalary());
            vo.setEmployeeCode(ee.getEmployeeCode());
            vo.setUpdateTime(ee.getUpdateTime());

            // 计算平均分（处理可能的空值和空列表情况）
            BigDecimal sumScore = assignmentEntities.stream()
                    .filter(entity -> entity.getTotalScore() != null)
                    .map(ProjectAssignmentEntity::getTotalScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //求值
            BigDecimal average = count > 0 ? sumScore.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            vo.setAvgScore(average);
            //增加
            vos.add(vo);
        }
        // 排序：先按 updateTime 降序，再按超期个数降序
//        List<EngineerEntityVO> sortedVos = vos.stream()
//                .sorted(
//                        Comparator.comparing(EngineerEntityVO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder()))
//                        .thenComparing(EngineerEntityVO::getOverdueProject, Comparator.reverseOrder())
//                ).collect(Collectors.toList());

        return TableDataInfo.build(list);
    }


}
